package org.example.rental.controller;

import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTPayload;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.rental.entity.Permission;
import org.example.rental.entity.User;
import org.example.rental.service.IUserService;
import org.example.rental.utils.JwtUtils;
import org.example.rental.utils.RedisUtils;
import org.example.rental.utils.Result;
import org.example.rental.utils.RouteTreeUtils;
import org.example.rental.vo.RouteVO;
import org.example.rental.vo.Tokenvo;
import org.example.rental.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author ：xxx
 * @description：TODO
 * @date ：2024/12/30 12:18
 */
@RestController
@RequestMapping("/rental/auth")
public class AuthController {
    @Autowired
    private RedisUtils redisUtils;
    @Resource
    private IUserService userService;
    @PostMapping("/refreshToken")
    public Result refreshToken(HttpServletRequest request){
        String token= request.getHeader("token");
        if(StrUtil.isEmpty(token)){
            token=request.getParameter("token");
        }
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails=(UserDetails) authentication.getPrincipal();
        String username= JwtUtils.parseToken(token).getClaim("username").toString();
        String newToken="";
        if(StrUtil.equals(username,userDetails.getUsername())){
            Map<String,Object>map=new HashMap<>();
            map.put("username",userDetails.getUsername());
            newToken=JwtUtils.createToken(map);
        }
        //获取本次token过期时间
        NumberWithFormat claim=(NumberWithFormat) JwtUtils.parseToken(newToken).getClaim(JWTPayload.EXPIRES_AT);
        DateTime dateTime =(DateTime)claim.convert(DateTime.class, claim);
        long expireTime=dateTime.getTime();
        Tokenvo tokenvo=new Tokenvo();
        tokenvo.setToken(newToken).setExpireTime(expireTime);
        //清除掉原有的token
        redisUtils.del("token:"+token);
        long nowTime=DateTime.now().getTime();
        String newTokenKey="token:"+newToken;
        redisUtils.set(newTokenKey,newToken,(expireTime-nowTime)/1000);
        return Result.success().setMessage("刷新token成功");
    }
    @GetMapping("/info")
    public Result getUserInfo(){
        Authentication authentication=SecurityContextHolder.getContext().getAuthentication();
        if(authentication==null){
            return Result.fail().setMessage("认证信息为空");
        }

        User user=(User)authentication.getPrincipal();
        List<String> list=userService.selectRoleName(user.getId());
        Object[]array=list.toArray();
        UserInfoVo userInfoVo=new UserInfoVo(user.getId(),user.getUsername(), user.getAvatar(), user.getNickname(),array);
        return Result.success(userInfoVo).setMessage("获取用户信息成功");
    }
    @GetMapping("/menuList")
    public Result getMenuList(){
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return Result.fail().setMessage("认证信息为空");
        }
        User user = (User) authentication.getPrincipal();
        //获取用户的权限列表
        List<Permission> permissionList = user.getPermissionList();
        //获取用户的菜单
        //将permission_type为2的按钮移除，不需要生成对应的菜单
        permissionList.removeIf(permission -> Objects.equals(permission.getPermissionType(), 2));
        List<RouteVO> routeVOList = RouteTreeUtils.buildRouteTree(permissionList, 0);
        return Result.success(routeVOList).setMessage("获取菜单列表成功");
    }

}
